<template>
  <view class="maintenance_detail_box">
    <!-- 类目选择 -->
    <view class="item">
      <uni-section title="维修类目" type="line">
        <uni-easyinput
          disabled
          trim="both"
          :value="maintenanceTitle"
          :inputBorder="!isRead"
          :styles="textareaStyles"
        />
      </uni-section>
    </view>

    <!-- 上门地址 -->
    <view class="item">
      <uni-section title="上门地址" type="line">
        <uni-easyinput
          disabled
          trim="both"
          :value="maintenanceAddress"
          :inputBorder="!isRead"
          :styles="textareaStyles"
        />
      </uni-section>
    </view>

    <!-- 电话号码输入 -->
    <view class="item">
      <uni-section title="电话号码" type="line">
        <uni-easyinput
          type="number"
          trim="both"
          :inputBorder="!isRead"
          :styles="textareaStyles"
          :disabled="isRead"
          v-model="maintenancePhone"
        />
      </uni-section>
    </view>

    <!-- 上门维修日期选择 -->
    <view class="item">
      <uni-section
        title="上门维修时间选择,请提前2个小时预约"
        sub-title="师傅上门服务时间于 8:00 ~ 20:30 请注意选择时间"
        type="line"
        :border="!isRead"
        titleFontSize="28rpx"
      >
        <uni-datetime-picker
          type="datetime"
          :disabled="isRead"
          :start="time.start"
          :end="time.end"
          :hide-second="true"
          v-model="maintenanceTime"
          @change="changeLog"
        />
      </uni-section>
    </view>

    <!-- 故障描述 -->
    <view class="item">
      <uni-section title="故障描述200字以内" type="line" titleFontSize="28rpx">
        <uni-easyinput
          :inputBorder="!isRead"
          type="textarea"
          :disabled="isRead"
          :styles="textareaStyles"
          autoHeight
          trim="both"
          v-model="maintenanceMsg"
          placeholder="请描述发生的故障问题"
          maxlength="200"
        />
      </uni-section>
    </view>

    <!-- 图片上传 -->
    <view class="item">
      <uni-section title="上传故障图片" type="line" titleFontSize="28rpx">
        <uni-file-picker
          limit="9"
          :readonly="isRead"
          v-model="imageValue"
          file-extname="png,jpg,svg"
          :imageStyles="imageStyles"
          title="最多选择9张图片"
          @select="selectFile"
          @delete="deleteFile"
        />
      </uni-section>
    </view>

    <!-- 备注内容 -->
    <view class="item">
      <uni-section
        title="备注内容200字以内（可选）"
        type="line"
        titleFontSize="28rpx"
      >
        <uni-easyinput
          :inputBorder="!isRead"
          type="textarea"
          :styles="textareaStyles"
          autoHeight
          trim="both"
          :disabled="isRead"
          v-model="remark"
          placeholder="您想要说些什么"
          maxlength="200"
        />
      </uni-section>
    </view>

    <!-- 刷新按钮 -->
    <view class="refresh_bth" @click="refresh">
      <uni-icons type="refreshempty" size="30" />
    </view>

    <!-- 提交按钮 -->
    <button-click
      backColor="rgb(10, 127, 251)"
      @on-click="onSubmit"
      :is-disable="isRead"
      msg="提交"
    />
  </view>
</template>

<!-- 维修详情、添加、修改页面 -->
<script lang="ts" setup>
import {
  MaintenanceStateEnum,
  getEnumValue,
} from '@/config/enum/enum'
import { useUserStore } from '@/store/user'
import {
  ReqAddMaintenance,
  ReqPutMaintenanceById,
  ReqSelectMaintenanceById,
} from '@/api/maintenance'
import { ReqUploadImage } from '@/api/upload'
import buttonClick from '@/components/common/button_click/button-click.vue'
import uniDatetimePicker from '@/components/common/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue'
import uniEasyinput from '@/components/common/uni-easyinput/components/uni-easyinput/uni-easyinput.vue'
import uniFilePicker from '@/components/common/uni-file-picker/components/uni-file-picker/uni-file-picker.vue'
import uniSection from '@/components/common/uni-section/components/uni-section/uni-section.vue'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

//是否只读
const isRead = ref(false)

//防止重复提交
const isReq = ref(true)

//维修标题
const maintenanceTitle = ref('')

//上门地址
const maintenanceAddress = ref('')

//维修id
const maintenanceId = ref(0)

//备注内容
const remark = ref('')

//电话号码
const maintenancePhone = ref('')

//故障内容描述
const maintenanceMsg = ref('')

//上门维修时间
const maintenanceTime = ref('')

//文件上传返回路径存储数组
const maintenanceImg = ref<string[]>([])

//图片回显数组
const imageValue = ref<any>([])

//图片样式
const imageStyles = ref({
  width: 110,
  height: 110,
  border: {
    radius: '10rpx',
  },
})

//内容文本框样式
const textareaStyles = ref({
  wordBreak: 'break-all',
  disableColor: '#fff',
})

//上门时间选择范围
const time = ref({
  start: '',
  end: '',
})

//初始化时间选择列表
const initDate = () => {
  //起始时间
  let nowTime = new Date()
  time.value.start = `${nowTime.getFullYear()}-${
    (nowTime.getMonth() + 1 < 10 ? '0' : '') + (nowTime.getMonth() + 1)
  }-${(nowTime.getDate() < 10 ? '0' : '') + nowTime.getDate()} 08:30`

  //截止时间
  let timestamp = Date.now() + 1000 * 60 * 60 * 24 * 7
  let endTime = new Date(timestamp)
  time.value.end = `${endTime.getFullYear()}-${
    (endTime.getMonth() + 1 < 10 ? '0' : '') + (endTime.getMonth() + 1)
  }-${(endTime.getDate() < 10 ? '0' : '') + endTime.getDate()} 20:30`
}

//时间选择确认时触发
const changeLog = (e: any) => {
  if (e == '' || !e) {
    return
  }
  //例如格式为 2024-06-07 18:56
  let nowTime = new Date()
  let dateArr = e.split(' ')
  //日期年月日
  let dayArr = dateArr[0].split('-')
  //小时、分钟
  let timeArr = dateArr[1].split(':')
  //选中时间的小时 要大于 当前小时3小时以后的时间
  if (
    nowTime.getDate() == parseInt(dayArr[2]) &&
    parseInt(timeArr[0]) < nowTime.getHours() + 2
  ) {
    uni.showToast({
      title: '上门时间须提前2个小时',
      icon: 'none',
      mask: true,
    })
    setTimeout(() => {
      maintenanceTime.value = ''
    }, 200)
    return
  }
  let hour = parseInt(timeArr[0]) < 8 || parseInt(timeArr[0]) > 20
  let minute = parseInt(timeArr[0]) == 20 && parseInt(timeArr[1]) > 30
  if (hour || minute) {
    uni.showToast({
      title: '上门时间 8:00 ~ 20:30',
      icon: 'none',
      mask: true,
    })
    setTimeout(() => {
      maintenanceTime.value = ''
    }, 200)
    return
  }
}

//图片文件选中时触发
const selectFile = (e: any) => {
  //上传文件
  if (e.tempFilePaths && e.tempFilePaths.length > 0) {
    e.tempFilePaths.forEach((f: string) => {
      ReqUploadImage(f)
        .then((res) => {
          if (res.code == 200 && res.data) {
            maintenanceImg.value.push(res.data[0])
          }
        })
        .catch((err) => {
          console.log(err)
        })
    })
  }
}

//图片文件删除时触发
const deleteFile = (e: any) => {
  imageValue.value.splice(e.index, 1)
  maintenanceImg.value.splice(e.index, 1)
}

//检查校验提交参数
const checkValue = () => {
  if (maintenanceTitle.value == '') {
    uni.showToast({
      title: '维修类目不能为空',
      icon: 'none',
      mask: true,
    })
    return false
  }
  if (maintenanceAddress.value == '') {
    uni.showToast({
      title: '上门地址不能为空',
      icon: 'none',
      mask: true,
    })
    return false
  }
  if (maintenancePhone.value == '') {
    uni.showToast({
      title: '请填写电话号码',
      icon: 'none',
      mask: true,
    })
    return false
  }
  if (maintenanceTime.value == '') {
    uni.showToast({
      title: '请选择上门维修时间',
      icon: 'none',
      mask: true,
    })
    return false
  }
  if (maintenanceMsg.value == '') {
    uni.showToast({
      title: '请描述故障问题',
      icon: 'none',
      mask: true,
    })
    return false
  }
  if (maintenanceImg.value.length < 1) {
    uni.showToast({
      title: '请拍摄故障图片',
      icon: 'none',
      mask: true,
    })
    return false
  }

  return true
}

//刷新、重置
const refresh = () => {
  initDate()
  if (isRead.value || maintenanceId.value) {
    getData()
    uni.pageScrollTo({ scrollTop: 0, duration: 0 })
  } else {
    //备注内容
    remark.value = ''

    //电话号码
    maintenancePhone.value = ''

    //故障内容描述
    maintenanceMsg.value = ''

    //上门维修时间
    maintenanceTime.value = ''

    //文件上传返回路径存储数组
    maintenanceImg.value = []

    //图片回显数组
    imageValue.value = []
  }
}

//已读状态下显示默认文本内容
const defaultRemarkText = () => {
  remark.value =
    isRead.value && (!remark.value || remark.value == '')
      ? '暂无内容'
      : remark.value
}

//提交维修内容
const onSubmit = async () => {
  if (!checkValue() || !isReq.value) {
    return
  }

  isReq.value = false

  //请求参数
  let query = {
    maintenanceId: maintenanceId.value,
    maintenanceTitle: maintenanceTitle.value,
    remark: remark.value == '' ? '暂无其他内容' : remark.value,
    maintenancePhone: maintenancePhone.value,
    maintenanceTime: maintenanceTime.value,
    maintenanceMsg: maintenanceMsg.value,
    maintenanceImg: maintenanceImg.value.join(','),
    maintenanceAddress: maintenanceAddress.value,
  }

  if (maintenanceId.value) {
    let resUpdate = await ReqPutMaintenanceById(query)
    toMaintenance(resUpdate.code, resUpdate.data)
  } else {
    let resAdd = await ReqAddMaintenance(query)
    toMaintenance(resAdd.code, resAdd.data)
  }

  isReq.value = true
}

//跳转我的维修页面
const toMaintenance = (code?: number, to: boolean | null = false) => {
  // 如果状态码不是200 表明请求出现问题
  if (!code || code != 200) {
    return
  }

  uni.showToast({
    title: to ? '成功提交' : '提交失败',
    icon: 'none',
    mask: true,
  })

  // 修改失败，直接结束
  if (!to) {
    return
  }

  setTimeout(() => {
    uni.navigateTo({ url: '/subpkg/maintenance/maintenance' })
  }, 500)
}

//查询维修订单内容
const getData = () => {
  if (!isReq.value) {
    return
  }
  uni.showLoading({
    title: '加载中',
    mask: true,
  })
  isReq.value = false
  ReqSelectMaintenanceById({ id: maintenanceId.value })
    .then((res) => {
      if (res.code == 200 && res.data) {
        maintenancePhone.value = res.data.maintenancePhone
        maintenanceTitle.value = res.data.maintenanceTitle
        maintenanceAddress.value = res.data.maintenanceAddress
        maintenanceTime.value = res.data.maintenanceTime.toString()
        maintenanceMsg.value = res.data.maintenanceMsg
        if (res.data.maintenanceState) {
          let category = getEnumValue(res.data.maintenanceState)
          isRead.value =
            category == MaintenanceStateEnum.CANCELED ||
            category == MaintenanceStateEnum.DONE
          defaultRemarkText()
        }
        let arr: any = []
        maintenanceImg.value = res.data.maintenanceImg.split(',')
        maintenanceImg.value.forEach((url) => {
          arr.push({
            url,
          })
        })
        imageValue.value = arr
        remark.value = res.data.remark
      }
    })
    .finally(() => {
      isReq.value = true
      uni.hideLoading()
    })
}

//页面加载
onLoad((e) => {
  //初始化时间范围选择
  initDate()
  if (e && e.id) {
    maintenanceId.value = e.id
    getData()
  } else if (e) {
    maintenanceTitle.value = `${e.category}-${e.msg}`
    maintenanceAddress.value = useUserStore().getHouseInfo
  }
})
</script>

<style scoped lang="scss">
.maintenance_detail_box {
  padding: 0 30rpx;
  width: calc(100% - 60rpx);

  .refresh_bth {
    position: fixed;
    bottom: 20%;
    right: 10%;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 90rpx;
    height: 90rpx;
    border-radius: 50%;
    background-color: $uni-bg-color;
    box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
    z-index: 90;
  }

  .item {
    margin-bottom: 30rpx;
  }
}
</style>
